#!/usr/bin/env node

const http=require('http'),
      fs=require('fs'),
      log=console.log;
//可简写
//http.createServer((req,res)=>{}).listen(8080);
//本质
const server=http.createServer();
server.listen(8080);

server.on('request',(req,res)=>{
  log(`${req.method} ${req.url} HTTP/${req.httpVersion}`);
  log(req.headers);
  log('');

  const file=__dirname+req.url;
  
  //res.end(fs.readFileSync(file).toString('utf8'));//把取出来的文件发送到客户端
  
  //错误处理
  fs.readFile(file,(err,data)=>{
    if(err){
      log(err.message);
      res.statusCode=404;
      res.end(err.message);
    }else{
      res.end(data);
    }
  })
  //res.write('hello');
  //res.end(' world!');
});



